<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCustomerList,
  addCustomer,
  updateCustomer,
  queryByIdApi
} from '@/api/customer'

// 枚举选项定义
const channelOptions = [
  { label: '线上活动', value: 1 },
  { label: '推广介绍', value: 2 }
]

const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 }
]

const degreeOptions = [
  { label: '高中', value: 1 },
  { label: '中专', value: 2 },
  { label: '大专', value: 3 },
  { label: '本科', value: 4 },
  { label: '硕士', value: 5 },
  { label: '博士', value: 6 },
  { label: '其他', value: 7 }
]

const jobStatusOptions = [
  { label: '在职', value: 1 },
  { label: '离职', value: 2 }
]

const subjectOptions = [
  { label: 'AI智能应用开发(java)', value: 1 },
  { label: 'AI大模型开发(python)', value: 2 },
  { label: 'AI鸿蒙开发', value: 3 },
  { label: 'AI大数据', value: 4 },
  { label: 'AI嵌入式', value: 5 },
  { label: 'AI测试', value: 6 },
  { label: 'AI运维', value: 7 }
]

const courseNameOptions = [
  { label: 'AI智能应用开发(Java)', value: 1 },
  { label: 'AI大模型开发(Python)', value: 2 },
  { label: 'AI鸿蒙开发', value: 3 },
  { label: 'AI大数据', value: 4 },
  { label: 'AI嵌入式', value: 5 },
  { label: 'AI测试', value: 6 },
  { label: 'AI运维', value: 7 }
]

// 格式化函数
const formatValue = (value, options) => {
  if (!value && value !== 0) return ''
  const option = options.find(opt => opt.value === Number(value))
  return option ? option.label : value
}

const formatChannel = (value) => formatValue(value, channelOptions)
const formatDegree = (value) => formatValue(value, degreeOptions)
const formatJobStatus = (value) => formatValue(value, jobStatusOptions)
const formatSubject = (value) => formatValue(value, subjectOptions)
const formatCourseName = (value) => formatValue(value, courseNameOptions)
const formatGender = (value) => formatValue(value, genderOptions)

// 页面加载完毕后, 执行查询
onMounted(() => {
  search()
})

// 查询参数
const queryParams = reactive({
  phone: '',
  name: '',
  channel: '',
  subject: '',
  page: 1,
  pageSize: 10,
  orderBy: 'id',
  orderType: 'desc'
})

// 表格数据
const customerList = ref([])
const total = ref(0)

// 搜索
const search = async () => {
  const response = await getCustomerList(queryParams)
  if (response.code === 1) {
    customerList.value = response.data.rows || []
    total.value = response.data.total || 0
  } else {
    ElMessage.error(response.msg || '获取客户列表失败')
  }
}

// 清空
const clear = () => {
  queryParams.phone = ''
  queryParams.name = ''
  queryParams.channel = ''
  queryParams.subject = ''
  queryParams.page = 1
  queryParams.pageSize = 10
  queryParams.orderBy = 'id'
  queryParams.orderType = 'desc'
  search()
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  search()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val
  search()
}



// 对话框
const formTitle = ref('')
const dialogFormVisible = ref(false)
const formLabelWidth = '100px'
const customer = reactive({
  id: '',
  name: '',
  phone: '',
  channel: '',
  degree: '',
  jobStatus: '',
  subject: '',
  courseName: '',
  gender: '',
  age: '',
  wechat: '',
  qq: ''
})

// 表单校验规则
const customerFormRef = ref(null)
const rules = reactive({
  name: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  channel: [
    { required: true, message: '请输入渠道来源', trigger: 'blur' }
  ],
  degree: [
    { required: true, message: '请输入学历', trigger: 'blur' }
  ],
  jobStatus: [
    { required: true, message: '请输入在职状态', trigger: 'blur' }
  ],
  subject: [
    { required: true, message: '请输入意向学科', trigger: 'blur' }
  ],
  courseName: [
    { required: true, message: '请输入意向课程', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 120, message: '年龄在1-120之间', trigger: 'blur' }
  ],
  wechat: [
    { required: true, message: '请输入微信号', trigger: 'blur' }
  ],
  qq: [
    { required: true, message: '请输入QQ号', trigger: 'blur' },
    { pattern: /^[1-9]\d{4,10}$/, message: '请输入正确的QQ号格式', trigger: 'blur' }
  ]
})

// 添加客户
const handleAdd = () => { 
  dialogFormVisible.value = true
  formTitle.value = '新增客户'
  customer.id = ''
  customer.name = ''
  customer.phone = ''
  customer.channel = ''
  customer.degree = ''
  customer.jobStatus = ''
  customer.subject = ''
  customer.courseName = ''
  customer.gender = ''
  customer.age = ''
  customer.wechat = ''
  customer.qq = ''

  if (customerFormRef.value) { // 如果表单存在
    customerFormRef.value.resetFields()
  }
}

// 保存客户
const save = async () => { 
  customerFormRef.value.validate(async (valid) => { // 表单校验 true:校验成功  false:校验失败
    if(valid){ //校验成功
      let response
      if(customer.id){ // 如果customer有id, 执行修改
        response = await updateCustomer(customer);
      }else{
        // 新增时需要创建新对象，避免提交id为空字符串
        const customerData = { ...customer }
        if (customerData.id === '') {
          delete customerData.id
        }
        response = await addCustomer(customerData);
      }
      
      if(response.code === 1){ //成功
          ElMessage.success('保存成功')
          dialogFormVisible.value = false
          search()
      }else { //失败
          ElMessage.error(response.msg || '保存失败')
      }
      
    }else {
      ElMessage.error('请填写正确的数据')
    }
  })
}

// 点击修改按钮触发
const handleEdit = async(id) => {
  const response = await queryByIdApi(id)
  if(response.code === 1){ //成功
    dialogFormVisible.value = true
    formTitle.value = '修改客户'
    customer.id = response.data.id
    customer.name = response.data.name
    customer.phone = response.data.phone
    customer.channel = response.data.channel
    customer.degree = response.data.degree
    customer.jobStatus = response.data.jobStatus
    customer.subject = response.data.subject
    customer.courseName = response.data.courseName
    customer.gender = response.data.gender || ''
    customer.age = response.data.age || ''
    customer.wechat = response.data.wechat || ''
    customer.qq = response.data.qq || ''

    if (customerFormRef.value) { // 如果表单存在
      customerFormRef.value.resetFields()
    }
  }else {
    ElMessage.error(response.msg || '获取客户详情失败')
  }
}

// 删除客户功能暂未启用，API未导入
// 如需启用，请在import语句中添加deleteCustomer API
</script>

<template>
  <div class="customer">
  	
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="queryParams" ref="queryForm" class="search-form">
      <el-form-item label="手机号">
        <el-input v-model="queryParams.phone" placeholder="请输入"/>
      </el-form-item>

      <el-form-item label="客户姓名">
        <el-input v-model="queryParams.name" placeholder="请输入"/>
      </el-form-item>

      <el-form-item label="渠道来源">
        <el-select v-model="queryParams.channel" placeholder="请选择" clearable>
          <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="意向学科">
        <el-select v-model="queryParams.subject" placeholder="请选择" clearable>
          <el-option
            v-for="item in subjectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item class="search-buttons">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 操作按钮区域 -->
    <div class="operation-area">
      <el-button type="primary" @click="handleAdd">新增客户</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table  :data="customerList"  style="width: 100%" border>
      <el-table-column prop="id" label="客户ID" width="80" align="center" />
      <el-table-column prop="name" label="客户姓名" width="120" align="center" />
      <el-table-column prop="phone" label="手机号" width="150" align="center" />
      <el-table-column prop="channel" label="渠道来源" width="120" align="center">
          <template #default="scope">
            {{ formatChannel(scope.row.channel) }}
          </template>
        </el-table-column>
      <el-table-column prop="degree" label="学历" width="100" align="center">
        <template #default="scope">
          {{ formatDegree(scope.row.degree) }}
        </template>
      </el-table-column>
      <el-table-column prop="jobStatus" label="在职状态" width="100" align="center">
        <template #default="scope">
          {{ formatJobStatus(scope.row.jobStatus) }}
        </template>
      </el-table-column>
      <el-table-column prop="subject" label="意向学科" width="180" align="center">
        <template #default="scope">
          {{ formatSubject(scope.row.subject) }}
        </template>
      </el-table-column>
      <el-table-column prop="courseName" label="意向课程" width="180" align="center">
        <template #default="scope">
          {{ formatCourseName(scope.row.courseName) }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row.id)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>


    <!-- 添加客户 / 修改客户 对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="formTitle" width="600px">
      <el-form ref="customerFormRef" :model="customer" :rules="rules" class="customer-form" :label-width="formLabelWidth">
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="customer.phone" autocomplete="off" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="客户姓名" :label-width="formLabelWidth" prop="name">
          <el-input v-model="customer.name" autocomplete="off" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
          <el-select v-model="customer.gender" placeholder="请选择">
            <el-option
              v-for="item in genderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
          <el-input v-model.number="customer.age" type="number" autocomplete="off" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="微信号" :label-width="formLabelWidth" prop="wechat">
          <el-input v-model="customer.wechat" autocomplete="off" placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="QQ" :label-width="formLabelWidth" prop="qq">
          <el-input v-model="customer.qq" autocomplete="off" placeholder="请输入"/>
        </el-form-item>
        
        <el-form-item label="渠道来源" :label-width="formLabelWidth" prop="channel">
          <el-select v-model="customer.channel" placeholder="请选择">
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="学历" :label-width="formLabelWidth" prop="degree">
          <el-select v-model="customer.degree" placeholder="请选择">
            <el-option
              v-for="item in degreeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="在职状态" :label-width="formLabelWidth" prop="jobStatus">
          <el-select v-model="customer.jobStatus" placeholder="请选择">
            <el-option
              v-for="item in jobStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="意向学科" :label-width="formLabelWidth" prop="subject">
          <el-select v-model="customer.subject" placeholder="请选择">
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="意向课程" :label-width="formLabelWidth" prop="courseName">
          <el-select v-model="customer.courseName" placeholder="请选择">
            <el-option
              v-for="item in courseNameOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
.customer {
  padding: 20px;
  background-color: #fff;
  min-height: 100%;
  border-radius: 8px;
}

.operation-area {
  margin: 20px 0;
}

.search-form {
  display: flex;
  align-items: center;
}

.search-form :deep(.el-form-item) {
  margin-right: 20px;
  min-width: 280px;
}

.search-buttons {
  margin-left: auto !important;
  min-width: auto !important;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.divider {
  height: 0.5px;
  background-color: #dcdfe6;
  margin: 10px 0;
  width: 100%;
}

:deep(.customer-dialog .el-dialog__body) {
  padding-top: 30px;
}

.customer-form {
  width: 80%;
  margin: 0 auto;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}
</style>
